package com.focusai.efairy.ui.activity.project;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.focusai.efairy.R;
import com.focusai.efairy.model.project.DevIccIdItem;
import com.focusai.efairy.model.request.GetDevIccDRequest;
import com.focusai.efairy.model.request.GetUserListRequest;
import com.focusai.efairy.model.response.DevIccDResponse;
import com.focusai.efairy.network.HttpManager;
import com.focusai.efairy.network.Response;
import com.focusai.efairy.network.exception.NetworkException;
import com.focusai.efairy.ui.adapter.base.BaseRecyclerAdapter;
import com.focusai.efairy.ui.adapter.base.BaseRecyclerViewHolder;
import com.focusai.efairy.ui.adapter.base.RecycleViewDivider;
import com.focusai.efairy.ui.adapter.project.ProjectSelectDevIccIdAdapter;
import com.focusai.efairy.ui.base.SwipeBackTipBaseActivity;
import com.focusai.efairy.utils.ScreenUtil;
import com.google.zxing.QrCodeCameraPreviewActivity;
import com.mylhyl.crlayout.SwipeRefreshAdapterView;
import com.mylhyl.crlayout.SwipeRefreshRecyclerView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by luo_guangwen on 2017/11/2.
 */

public class ProjectSelectDevIccDActivity extends SwipeBackTipBaseActivity implements SwipeRefreshLayout.OnRefreshListener,View.OnClickListener,
        SwipeRefreshAdapterView.OnListLoadListener {
    public static final String KEY_CCID = "key_ccid";
    private static final int REQUEST_CODE_SCAN = 0x11;

    private SwipeRefreshRecyclerView mRefreshRecyclerView;
    private ImageView searchClearIcon;
    private EditText txtSearchedit;
    private ProjectSelectDevIccIdAdapter mAdapter;
    private List<DevIccIdItem> mList;
    private String mKeyword = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_dev_select_iccid);
        initView();
        setDefaultValues();
    }

    @Override
    protected boolean hasActionBar() {
        return false;
    }

    @Override
    protected void initView() {
        mRefreshRecyclerView = findView(R.id.swipe_recyce_view);
        searchClearIcon = findView(R.id.search_header_clear);
        txtSearchedit = findView(R.id.txtSearchedit);
        findView(R.id.search_header_clear).setOnClickListener(this);
        findView(R.id.text_cancal_searchBtn).setOnClickListener(this);
    }

    @Override
    protected void setDefaultValues() {
        mAdapter = new ProjectSelectDevIccIdAdapter(getContext());
        mList = new ArrayList<>();
        mRefreshRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRefreshRecyclerView.setAdapter(mAdapter);
        mRefreshRecyclerView.getScrollView().addItemDecoration(new RecycleViewDivider(
                mContext, LinearLayoutManager.VERTICAL, ScreenUtil.dp2pix(1), getResources().getColor(R.color.main_line_gray)));
        mAdapter.refreshData(mList);
        mRefreshRecyclerView.setOnListLoadListener(this);
        mRefreshRecyclerView.setOnRefreshListener(this);
        mAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseRecyclerViewHolder holder) {
                int position = mRefreshRecyclerView.getScrollView().getChildLayoutPosition(holder.itemView);
                DevIccIdItem item = mList.get(position);
                if (item != null){
                    Intent intent = new Intent();
                    intent.putExtra(KEY_CCID,item.efairyiotcard_number);
                    setResult(RESULT_OK,intent);
                    finish();
                }
            }
        });
        txtSearchedit.setFocusable(true);
        txtSearchedit.setFocusableInTouchMode(true);
        txtSearchedit.requestFocus();
        txtSearchedit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String keyword = txtSearchedit.getText().toString();
                if (keyword == null || keyword.length() <= 0) {
                    searchClearIcon.setImageResource(R.drawable.btn_scan);
                    mKeyword = "";
                } else {
                    searchClearIcon.setImageResource(R.drawable.search_btn_cancel_nor);
                    mKeyword = keyword;
                    refresh();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        txtSearchedit.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                String keywork = txtSearchedit.getText().toString();
                if (!TextUtils.isEmpty(keywork)) {
                    mKeyword = keywork;
                    refresh();
                }
                return true;
            }
        });
        mRefreshRecyclerView.setRefreshing(true);

    }

    @Override
    public void onRefresh() {
        refresh();
    }

    @Override
    public void onListLoad() {
        loadMore();
    }

    private void refresh() {
        HttpManager.getInstance().sendRequest(new GetDevIccDRequest( 0, mKeyword,
                new Response.Listener<DevIccDResponse>() {
                    @Override
                    protected void onSuccess(DevIccDResponse response) {
                        if (response != null && response.efairyiotcard_list != null) {
                            mList.clear();
                            mList.addAll(response.efairyiotcard_list);
                            mAdapter.notifyDataSetChanged();
                            if (GetUserListRequest.size > mList.size()) {
                                mRefreshRecyclerView.setEnabledLoad(false);
                            } else {
                                mRefreshRecyclerView.setEnabledLoad(true);
                            }
                            mRefreshRecyclerView.setRefreshing(false);
                        }
                        showTip(mList);
                    }

                    @Override
                    protected void onFail(NetworkException exception) {
                        mRefreshRecyclerView.setRefreshing(false);
                        doException(exception);
                        showTip(mList);
                    }
                }));
    }

    private void loadMore() {
        if (mList.size() == 0) {
            mRefreshRecyclerView.setLoading(false);
            return;
        }
        HttpManager.getInstance().sendRequest(new GetDevIccDRequest(mList.get(mList.size() - 1).efairyiotcard_id, mKeyword,
                new Response.Listener<DevIccDResponse>() {
                    @Override
                    protected void onSuccess(DevIccDResponse response) {
                        if (response != null && response.efairyiotcard_list != null) {
                            mList.addAll(response.efairyiotcard_list);
                            mAdapter.notifyDataSetChanged();
                            if (mList.size() == response.total_rows) {
                                mRefreshRecyclerView.setEnabledLoad(false);
                            } else {
                                mRefreshRecyclerView.setEnabledLoad(true);
                            }
                            mRefreshRecyclerView.setLoading(false);
                        }
                    }

                    @Override
                    protected void onFail(NetworkException exception) {
                        mRefreshRecyclerView.setLoading(false);
                        doException(exception);
                    }
                }));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_SCAN:
                    if (data != null ){
                        Bundle bundle = data.getExtras();
                        String scanResult = bundle.getString("result");
                        if (!TextUtils.isEmpty(scanResult)){
//                            Intent intent = new Intent();
//                            intent.putExtra(KEY_CCID,scanResult);
//                            setResult(RESULT_OK,intent);
//                            finish();
                            txtSearchedit.setText(scanResult);
                        }
                    }
                    break;
                default:
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.text_cancal_searchBtn:
                finish();
                break;
            case R.id.search_header_clear:
                if (TextUtils.isEmpty(txtSearchedit.getText().toString())){
                    Intent intent = new Intent(getContext(), QrCodeCameraPreviewActivity.class);
                    startActivityForResult(intent, REQUEST_CODE_SCAN);
                }else {
                    txtSearchedit.setText("");
                    mKeyword = "";
                    refresh();
                }
                break;
            default:
                break;
        }
    }
}
